<script setup lang="tsx">
import { ContentWrap } from "@/components/ContentWrap";
import { useI18n } from "@/hooks/web/useI18n";
import { Table } from "@/components/Table";
import { reactive, unref, h, ref } from "vue";
import { ElTag, ElRadioButton, ElRadioGroup } from "element-plus";
import EditEvent from "./components/EditEvent.vue";
import Detail from "./components/Detail.vue";
import { useTable } from "@/hooks/web/useTable";
import { BaseButton } from "@/components/Button";
import { Dialog } from "@/components/Dialog";
import { CrudSchema, useCrudSchemas } from "@/hooks/web/useCrudSchemas";
import { EmergencyEventType } from "@/api/Emergency/type";
import Distribute from "./components/Distribute.vue";
import EmergencyApi from "@/api/Emergency";
import { useDictStore } from "@/store/modules/dictData";
const { tableRegister, tableState, tableMethods } = useTable({
  fetchDataApi: async () => {
    const { currentPage, pageSize } = tableState;
    const res = await EmergencyApi.GetEmergencyInfo({
      pageNum: unref(currentPage),
      pageSize: unref(pageSize),
      ...unref(searchParams),
    });
    return {
      list: res.rows,
      total: res.total,
    };
  },
  fetchDelApi: async () => {
    const res = await EmergencyApi.DeletEmergencyInfo(unref(ids)[0]);
    return !!res;
  },
});
const DictStore = useDictStore();
DictStore.setDict("event_state"); //状态字典
DictStore.setDict("event_group"); //工单归属字典
DictStore.setDict("hazard_type"); //隐患类型字典
DictStore.setDict("hazard_level"); //隐患等级字典
const { loading, dataList, total, currentPage, pageSize } = tableState;
const { getList, getElTableExpose, delList } = tableMethods;
const { t } = useI18n();
const crudSchemas = reactive<CrudSchema[]>([
  {
    field: "selection",
    type: "selection",
    form: {
      hidden: true,
    },
    detail: {
      hidden: true,
    },
    fixed: "left",
  },
  {
    field: "index",
    label: t("tableDemo.index"),
    type: "index",
    fixed: "left",
    form: {
      hidden: true,
    },
    detail: {
      hidden: true,
    },
  },
  {
    field: "eventState",
    label: t("状态"),
    width: 150,
    formatter: (_: Recordable, __: any, cellValue: string) => {
      return DictStore.$state.event_state?.map((item) => {
        if (item.dictValue == cellValue) {
          return h(ElTag, { type: item.listClass }, () => t(item.dictLabel));
        }
      });
    },
    form: {
      hidden: true,
    },
    detail: {
      slots: {
        default: (data: any) => {
          return DictStore.$state.event_state?.map((item) => {
            if (item.dictValue == data.eventState) {
              return <ElTag type={item.listClass}>{t(item.dictLabel)}</ElTag>;
            }
          });
        },
      },
    },
    table: {
      hidden: false,
    },
  },
  {
    field: "serialNo",
    label: t("工单编号"),
    width: 150,
    form: {
      component: "Input",
      colProps: {
        span: 20,
      },
      componentProps: {
        disabled: true,
      },
    },
    detail: {
      hidden: false,
    },
    table: { hidden: false },
  },
  {
    field: "hazardLevel",
    label: t("隐患等级"),
    width: 150,
    formatter: (_: Recordable, __: any, cellValue: string) => {
      return DictStore.$state.hazard_level?.map((item) => {
        if (item.dictValue == cellValue) {
          return h(ElTag, { effect: "dark", type: item.listClass }, () =>
            t(item.dictLabel)
          );
        }
      });
    },
    form: {
      component: "RadioGroup",
      colProps: {
        span: 20,
      },
      componentProps: {
        options: DictStore.$state.hazard_level?.map((item) => {
          return {
            label: item.dictLabel,
            value: item.dictValue,
          };
        }),
      },
    },
    detail: {
      slots: {
        default: (data: any) => {
          return DictStore.$state.hazard_level?.map((item) => {
            if (item.dictValue == data.hazardLevel) {
              return item.dictLabel;
            }
          });
        },
      },
    },
  },
  {
    field: "eventGroup",
    label: t("工单归属"),
    width: 150,
    formatter: (_: Recordable, __: any, cellValue: string) => {
      return DictStore.$state.event_group?.map((item) => {
        if (item.dictValue == cellValue) {
          return t(item.dictLabel);
        }
      });
    },
    form: {
      component: "RadioGroup",
      colProps: {
        span: 20,
      },
      componentProps: {
        options: DictStore.$state.event_group?.map((item) => {
          return {
            label: item.dictLabel,
            value: item.dictValue,
          };
        }),
      },
    },
    detail: {
      slots: {
        default: (data: any) => {
          return DictStore.$state.event_group?.map((item) => {
            if (item.dictValue == data.eventGroup) {
              return item.dictLabel;
            }
          });
        },
      },
    },
  },
  {
    field: "eventId",
    label: t("事件类型"),
    width: 100,
    form: {
      hidden: true,
    },
  },
  {
    field: "hazardType",
    label: t("隐患类型"),
    width: 150,
    formatter: (_: Recordable, __: any, cellValue: string) => {
      return DictStore.$state.hazard_type?.map((item) => {
        if (item.dictValue == cellValue) {
          return t(item.dictLabel);
        }
      });
    },
    form: {
      component: "RadioGroup",
      colProps: {
        span: 20,
      },
      componentProps: {
        options: DictStore.$state.hazard_type?.map((item) => {
          return {
            label: item.dictLabel,
            value: item.dictValue,
          };
        }),
      },
    },
    detail: {
      slots: {
        default: (data: any) => {
          return DictStore.$state.hazard_type?.map((item) => {
            if (item.dictValue == data.hazardType) {
              return item.dictLabel;
            }
          });
        },
      },
    },
  },
  {
    field: "contacts",
    label: t("联系人"),
    width: 100,
    form: {
      hidden: false,
    },
  },
  {
    field: "contactPhone",
    label: t("联系电话"),
    width: 150,
    form: {
      hidden: false,
    },
  },
  {
    field: "address",
    label: t("事件描述"),
    width: 150,
    form: {
      hidden: false,
      colProps: {
        span: 20,
      },
    },
    detail: {
      span: 24,
    },
  },
  {
    field: "address",
    label: t("事件地址"),
    width: 150,
    form: {
      hidden: false,
      colProps: {
        span: 20,
      },
    },
    detail: {
      span: 24,
    },
  },
  {
    field: "createBy",
    label: t("创建人"),
    width: 100,
    form: {
      hidden: true,
    },
  },
  {
    field: "createTime",
    label: t("创建时间"),
    width: 200,
    form: {
      hidden: true,
    },
    detail: {
      span: 24,
    },
  },
  {
    field: "action",
    label: t("tableDemo.action"),
    width: 200,
    fixed: "right",
    form: {
      hidden: true,
    },
    detail: {
      hidden: true,
    },
    slots: {
      default: (data) => {
        return (
          <>
            <span class="TableBtn" onClick={() => action(data.row, "Detail")}>
              {t("查看")}
            </span>
            <span class="TableBtn" onClick={() => action(data.row, "Distribute")}>
              {t("指派")}
            </span>
            <span class="TableBtn" onClick={() => action(data.row, "Edit")}>
              {t("修改")}
            </span>
            <span
              class="TableBtn"
              style="color:#f56c6c"
              onClick={() => delData(data.row)}
            >
              {t("删除")}
            </span>
          </>
        );
      },
    },
  },
]);
const { allSchemas } = useCrudSchemas(crudSchemas);
const saveLoading = ref(false);
const dialogVisible = ref(false);
const dialogTitle = ref("添加");
const actionType = ref("");
const currentRow = ref<EmergencyEventType | null>(null);
//表格操作
const action = (row: EmergencyEventType, type: string) => {
  actionType.value = type;
  dialogVisible.value = true;
  currentRow.value = row;
  //   Distribute派发
  if (type == "Edit") {
    dialogTitle.value = "修改";
  } else if (type == "Detail") {
    dialogTitle.value = "详情";
  } else {
    dialogTitle.value = "派发";
  }
};
const delLoading = ref(false);
const ids = ref<string[]>([]);
//删除轨迹
const delData = async (row: EmergencyEventType) => {
  const elTableExpose = await getElTableExpose();
  ids.value = row
    ? [row.uuid]
    : elTableExpose?.getSelectionRows().map((v: EmergencyEventType) => v.uuid) || [];
  delLoading.value = true;
  await delList(unref(ids).length).finally(() => {
    delLoading.value = false;
  });
};
const writeRef = ref();
const save = async () => {
  const write = unref(writeRef);
  const formData = await write?.submit();
  if (formData) {
    saveLoading.value = true;
    saveLoading.value = false;
    const res: any = ref(false);
    if (actionType.value == "Edit") {
      res.value = await EmergencyApi.EditEmergencyInfo(formData)
        .catch(() => {})
        .finally(() => {
          saveLoading.value = false;
        });
    } else {
      res.value = await EmergencyApi.AddPlanEventAssign(formData)
        .catch(() => {})
        .finally(() => {
          saveLoading.value = false;
        });
    }

    if (res.value) {
      dialogVisible.value = false;
      currentPage.value = 1;
      getList();
    }
  }
};
const EventState = ref("all");
const EventType = ref("all");
const searchParams = ref({});
const EventChange = () => {
  if (EventState.value == "all" && EventType.value == "all") {
    searchParams.value = { eventState: "", eventGroup: "" };
  } else if (EventState.value == "all" && EventType.value !== "all") {
    searchParams.value = { eventState: "", eventGroup: EventType.value };
  } else if (EventState.value !== "all" && EventType.value == "all") {
    searchParams.value = { eventState: EventState.value, eventGroup: "" };
  } else {
    searchParams.value = { eventState: EventState.value, eventGroup: EventType.value };
  }
  getList();
};
</script>

<template>
  <ContentWrap title="应急处置台账管理">
    <ElRadioGroup
      @change="EventChange"
      v-model="EventState"
      style="margin: 0 30px 10px 0"
    >
      <ElRadioButton value="all">全部 </ElRadioButton>
      <ElRadioButton
        v-for="item in DictStore.$state.event_state"
        :key="item.dictValue"
        :value="item.dictValue"
      >
        {{ item.dictLabel }}
      </ElRadioButton>
    </ElRadioGroup>
    <ElRadioGroup @change="EventChange" v-model="EventType" style="margin: 0 10px 0 0">
      <ElRadioButton value="all"> 全部 </ElRadioButton>
      <ElRadioButton
        v-for="item in DictStore.$state.event_group"
        :key="item.dictValue"
        :value="item.dictValue"
      >
        {{ item.dictLabel }}
      </ElRadioButton>
    </ElRadioGroup>
    <Table
      v-model:pageSize="pageSize"
      v-model:currentPage="currentPage"
      :columns="allSchemas.tableColumns"
      :data="dataList"
      row-key="uuid"
      :loading="loading"
      :pagination="{
        total: total,
      }"
      @register="tableRegister"
    />
  </ContentWrap>
  <Dialog v-model="dialogVisible" :title="dialogTitle">
    <EditEvent
      v-if="actionType == 'Edit'"
      ref="writeRef"
      :form-schema="allSchemas.formSchema"
      :current-row="currentRow"
    />

    <Detail
      v-if="actionType === 'Detail'"
      :detail-schema="allSchemas.detailSchema"
      :current-row="currentRow"
    />
    <Distribute
      v-if="actionType == 'Distribute'"
      ref="writeRef"
      :current-row="currentRow"
    />
    <template #footer>
      <BaseButton type="primary" :loading="saveLoading" @click="save">
        {{ t("提交") }}
      </BaseButton>
      <BaseButton @click="dialogVisible = false">{{ t("关闭") }}</BaseButton>
    </template>
  </Dialog>
</template>

<style scoped>
.el-button {
  margin-top: 10px;
}
:deep(.TableBtn) {
  margin: 0 5px;
  font-size: 12px;
  cursor: pointer;
  color: #409eff;
  font-weight: 600 !important;
}
</style>
